<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-24 12:09:48
component:     updateStatus
Copyright © YourCompanyName All rights reserved
-->
<template>
  <el-dialog
    :destroy-on-close="true"
    title="修改订单状态"
    v-model="isVisible"
    @close="handleClose"
    width="600px"
  >
    <el-form :model="formData" ref="formRef" :rules="rules">
      <el-form-item label="物流类型" prop="logisticStatus">
        <el-select placeholder="请选择物流类型" v-model="formData.logisticStatus">
          <el-option
            v-for="option in props.presetLogisticStatusList || logisticStatusList"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { FormRules } from 'element-plus'
import { reactive } from 'vue'
import { ref, watch, defineProps, defineEmits } from 'vue'
import { updateLogistics } from '@/api/logistics'

const logisticStatusList = ref([
  { label: '拒签件', value: 3 },
  { label: '已签收', value: 4 },
  { label: '已退件', value: 6 }
])
// 定义组件的 props
interface Props {
  visible: boolean
  orderId: number
  presetLogisticStatusList?: { label: string; value }[]
}
const rules = reactive<FormRules>({
  logisticStatus: [{ required: true, message: '请选择物流状态', trigger: 'blur' }]
})

// 获取 props 和 emits
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void // 添加 success 事件
}>()

// 局部状态变量，用于管理弹窗的可见性
const isVisible = ref<boolean>(props.visible)
const loading = ref(false)

// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
  formData.value.logisticStatus = undefined
}
const formRef = ref()
const formData = ref({
  logisticStatus: undefined
})
// 保存备注的处理函数
const handleSave = async () => {
  loading.value = true
  try {
    await formRef.value?.validate()
    const res = await updateLogistics([
      {
        orderId: props.orderId,
        logisticStatus: formData.value.logisticStatus as unknown as number
      }
    ])
    if (res.code === 0) {
      emit('success') // 通知父组件
      handleClose() // 保存后关闭弹窗
      loading.value = false
    }
  } catch (e) {
    loading.value = false
    console.error(e)
  }
}
watch(
  () => props.visible,
  (newValue) => {
    isVisible.value = newValue
  }
)
</script>
